package test.n00600;

public class Problem00611 {
    public static void main(String[] args) {
        println(new int[]{1, 2, 3, 4, 5}, 2);
        println(new int[]{0, 1, 2}, 4);
        println(new int[]{}, 4);
        println(new int[]{1}, 1);
    }


    public static void println(int[] array, int k) {
        if (array == null || array.length == 0) {
            return;
        }
        Solution s = new Solution();
        ListNode node = s.rotateRight(create(array), k);

        while (true) {
            System.out.print(node.val + ",");
            node = node.next;

            if (node == null) {
                System.out.println();
                break;
            }
        }
    }

    public static ListNode create(int[] a1) {
        if (a1.length == 0) {
            return null;
        }
        ListNode[] list = new ListNode[a1.length];
        for (int i = 0; i < a1.length; i++) {
            list[i] = new ListNode(a1[i]);
            if (i > 0) {
                list[i - 1].next = list[i];
            }
        }

        return list[0];
    }


    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    private static class Solution {
        /**
         * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
         * <p>
         * 解题思路:
         * 1.尾节点指向头节点
         * 2.移动节点到最后一个节点，并指向null
         *
         * @param head
         * @param k
         * @return
         */
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || k == 0 || head.next == null) {
                return head;
            }

            ListNode iter = head;
            int len = 1;
            while (iter.next != null) {
                iter = iter.next;
                len++;
            }

            if (len <= 1 || k % len == 0) {
                return head;
            }

            // 尾节点指向头节点
            iter.next = head;

            int nextMoveNum = len - (k % len);
            while (nextMoveNum > 0) {
                nextMoveNum--;
                iter = iter.next;
            }

            ListNode ret = iter.next;
            iter.next = null;
            return ret;
        }

        private int getNodeLength(ListNode head) {
            ListNode t = head;
            int len = 0;
            while (t != null) {
                t = t.next;
                len++;
            }
            return len;
        }
    }
}
